<?php
namespace app\appapi\controller;
use think\Controller;
use think\Request;
use think\Db;
use app\appapi\WeShare;
use app\appapi\WXBizDataCrypt;

class WeBusinesscard extends Common

{
    //更新添加个人名片
    public function getAddUserCardInfo()
    {
        $data = input('post.');
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        if(empty($data['uid']) || !$data['uid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
        unset($data['uid']);
        $time = time();
        $arr['Realname'] = $data['Realname'];
        $arr['Company'] = $data['Company'];
        $arr['Position'] = $data['Position'];
        if(!empty($data['Card_address']))
        $arr['Card_address'] = $data['Card_address'];
        if(!empty($data['Province']))
        $arr['Province'] = $data['Province'];
        if(!empty($data['City']))
        $arr['City'] = $data['City'];
        if(!empty($data['County']))
        $arr['County'] = $data['County'];
        $arr['Phone'] = $data['Phone'];
        $arr['Wechat'] = $data['Wechat'];
        if(!empty($data['Card_portrait']))
        $arr['Card_portrait'] = $data['Card_portrait'];
        if(!empty($data['Campus']))
        $arr['Campus'] = $data['Campus'];
        if(!empty($data['Poster']))
        $arr['Poster'] = $data['Poster'];
        if(!empty($data['Introduce']))
        $arr['Introduce'] = $data['Introduce'];
        if(!empty($data['Industry']))
        $arr['Industry'] = $data['Industry'];
        if(!empty($data['Hobby']))
        $arr['Hobby'] = $data['Hobby'];
        if(!empty($data['Age']))
        $arr['Age'] = $data['Age'];
        if(!empty($data['Gender']))
        $arr['Gender'] = $data['Gender'];
        if($re = $this->_judgeUserCardInfo($uid)){
            // if($time - $re['Addtime']<30*24*3600)
            // return json_encode(['code'=>10002,'msg'=>'名片30天内仅能修改一次']);
			$where['User_id'] = ['=',$uid];
			Db::startTrans();
			try{
				if(Db::name('user_card')->where($where)->update($arr)){
					//确认更新成功再更新时间
					Db::name('user_card')->where($where)->setField('Addtime',$time);
					Db::commit();
					return json_encode(['code'=>10001,'msg'=>'更新成功','data'=>$arr]);
				}
				return json_encode(['code'=>10002,'msg'=>'更新失败']);
			}catch(\Exception $e){
				Db::rollback();
				return json_encode(['code'=>10002,'msg'=>'更新失败']);
			}
        }else{
			$arr['Addtime'] = $time;
            $arr['User_id'] = $uid;
            if(Db::name('user_card')->insert($arr))
            return json_encode(['code'=>10001,'msg'=>'更新成功','data'=>$arr]);
        }
        return json_encode(['code'=>10002,'msg'=>'更新失败']);
    }

    //统一更新单个名片信息
    public function getUpdateUserCardInfo()
    {
        $data = input('post.');
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        if(empty($data['uid']) || !$data['uid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
        unset($data['uid']);
        if(empty($data['field']) || !$data['field'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $field = $data['field'];
        unset($data['field']);
        $where['User_id'] = ['=',$uid];
        if(!$re = $this->_judgeUserCardInfo($uid)){//没有就添加
            //或者返回提示信息
            return json_encode(['code'=>10002,'msg'=>'请先完善名片信息']);
        }else{
            if($field == 'Hobby' || $field == 'Industry' || $field == 'Campus' || $field == 'Hometown'){
                $time = time();
                if($time - $re['Addtime']<30*24*3600)
                return json_encode(['code'=>10002,'msg'=>'兴趣爱好、从事行业、毕业院校、家乡地址30天内仅能修改一次']);
            }
            
            if($field == 'Hometown') $field = "Province,City,County";
            $re = Db::name('user_card')->where($where)->field($field)->update($data);
        }
        if($re)
        return json_encode(['code'=>10001,'msg'=>'更新成功','data'=>$data]);
        return json_encode(['code'=>10002,'msg'=>'更新失败']);
    }

    // //上传图片
	// public function getUploadPosterLocal()
	// {

    //     $files = $_FILES;
    //     $file = $files['file'];
    //     $fileName = '';
    //     $path='other/';
	// 	//$file = json_decode($file, true);
	// 	if(empty($file) || $file=='' || !$file) 
	// 	return json_encode(['code'=>10002,'msg'=>'上传失败']);		
	// 	// 获取图片    
	// 	//list($type, $data) = explode(',', $file);    
    //     $type = $file['type'];				
	// 	// 判断类型    
	// 	if(strstr($type,'image/jpeg')!=''){    
	// 		$ext = '.jpg';    
	// 	}elseif(strstr($type,'image/gif')!=''){    
	// 		$ext = '.gif';    
	// 	}elseif(strstr($type,'image/png')!=''){    
	// 		$ext = '.png';    
	// 	}    	
	// 	if (!is_dir($path)){  
	// 		//第三个参数是“true”表示能创建多级目录，iconv防止中文目录乱码
	// 		mkdir(iconv("UTF-8", "GBK", $path),0777,true);
	// 	}	
	// 	// 生成的文件名   
	// 	$fileName = $fileName?$fileName:time();
	// 	$paths = $path.$fileName.$ext;   
	// 	// 生成文件      
	// 	if(file_put_contents($paths, base64_decode($file), false))     
    //     return json_encode(['code'=>10002,'msg'=>'上传成功','data'=>dirname($_SERVER['SCRIPT_NAME']).'/'.$paths]);	  
	// 	return json_encode(['code'=>10002,'msg'=>'网络异常']);
	// }

    //上传图片
    public function getUploadFileLocal()
    {
        $file = request()->file('file');
        $data = $_REQUEST;
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        if(empty($data['uid']) || !$data['uid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        if($file) {
            //$paths = 'public/upload/wxHead/';//本地解开
            $paths = '../public/upload/wxHead/';
            $info = $file->move($paths);    
            $db = Db::name('user_poster');                
            if ($info) {
                $filename = $info->getSaveName();
                $filename = str_replace('\\', '/', $filename);
                //$url = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['SCRIPT_NAME']).'/public/upload/wxHead/'.$filename;//本地解开
                $url = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['SCRIPT_NAME']).'/upload/wxHead/'.$filename;                                                                  
                header('content-type:application/json;charset=utf-8');
                return json_encode(['code'=>10001,'msg'=>'上传成功','data'=>$url]);             
            }
            return json_encode(['code'=>10002,'msg'=>'上传失败']);
        }
       
    }

    //上传海报
    public function getUploadPosterLoading()
    {
        $file = request()->file('file');
        $data = $_REQUEST;
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        if(empty($data['uid']) || !$data['uid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
        $id = !empty($data['id'])?$data['id']:0;
        $where['User_id'] = ['=',$uid];
        $where['id'] = ['=',$id];
        $arr = array();
        $poster = array();
        if($file) {
            //$paths = 'public/upload/weixin/';//本地解开
            $paths = '../public/upload/weixin/';
            $info = $file->move($paths);    
            $db = Db::name('user_poster');                
            if ($info) {
                $filename = $info->getSaveName();
                $filename = str_replace('\\', '/', $filename);
                //$url = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['SCRIPT_NAME']).'/public/upload/weixin/'.$filename;//本地解开
                $url = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['SCRIPT_NAME']).'/upload/weixin/'.$filename;
                if(!$re = $db->where($where)->find()){
                    $arr = [
                        'User_id' => $uid,
                        'Url' => $url,
                    ];
                    $count = $db->where(array('User_id'=>$uid))->count();
                    if($count>10)
                    return json_encode(['code'=>10002,'msg'=>'上传失败，超过数量限制']);
                    $re = $db->insertGetId($arr);
                }else{
                    $file = $db->where($where)->value('Url');
                    if($re = $db->where($where)->update(array('Url'=> $url))){
                        deleFile($file);
                    }
                }                                                                  
                header('content-type:application/json;charset=utf-8');
                if($re){
                    $arr = $db->where(array('User_id'=>$uid))->field('id,Url')->select();
                    return json_encode(['code'=>10001,'msg'=>'上传成功','data'=>$arr]);
                }
                
            }
            return json_encode(['code'=>10002,'msg'=>'上传失败']);
        }
       
    }
    //删除海报
    public function getDellUserPost($value='')
    {
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
        if(empty($data['uid']) || !$data['uid'] || empty($data['id']) || !$data['id'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
        $id = $data['id'];
        $where['User_id'] = ['=',$uid];
        $where['id'] = ['=',$id];
        $db = Db::name('user_poster');    
        if(!$file = $db->where($where)->value('Url'))
        return json_encode(['code'=>10002,'msg'=>'删除失败']);
        if($db->where($where)->delete()){
            deleFile($file);
            $arr = $db->where(array('User_id'=>$uid))->field('id,Url')->select();
            return json_encode(['code'=>10001,'msg'=>'删除成功','data'=>$arr]);
        }
        return json_encode(['code'=>10002,'msg'=>'删除失败']);
    }
    //检测用户名片信息
    private function _judgeUserCardInfo($uid)
    {
        $where['User_id'] = ['=',$uid];
        if($re = Db::name('user_card')->where($where)->find())
        return $re;
        return false;
    }
    //获取用户绑定微信手机号
    public function getUserWxBindingPhone()
    {
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
        if(empty($data['uid']) || !$data['uid'] || empty($data['iv']) || !$data['iv'] || empty($data['encryptedData']) || !$data['encryptedData'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
        $iv = $data['iv'];
        $encryptedData = $data['encryptedData'];
        $weapp = new WeShare(); 
        $wAppconfig = getWxconfig('weAppSystem');//微信小程序配置
        $appid = $wAppconfig['app_id'];
		if(!empty($data['ss_key']) && $data['ss_key'] && $data['ss_key'] !=''){
			$sessionKey = $data['ss_key'];
		}else{
			if(empty($data['code']) || !$data['code'] )
			return json_encode(['code'=>10002,'msg'=>'code参数错误']);
			$code = $data['code'];
			$secret = $wAppconfig['secret'];
			$grant_type='authorization_code';
			$url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=$grant_type";
			$result = $weapp->getDataCurl($url);
			if(!$result || empty($result['session_key']))
			return json_encode(['code'=>10002,'msg'=>'网络异常']);
			$sessionKey = $result['session_key'];
		}
        $pc = new WXBizDataCrypt($appid, $sessionKey);
        $arr = $pc->decryptData($encryptedData, $iv);
        if($arr){
            unset($arr['watermark']);
            return json_encode(['code'=>10001,'msg'=>'解密成功','data'=>$arr]);
        }
        return json_encode(['code'=>10002,'msg'=>'网络繁忙']);
    }
}
